package org.weixin4j.spi;

import java.util.Date;
import java.util.UUID;

import org.weixin4j.Configuration;
import org.weixin4j.User;
import org.weixin4j.Weixin;

import beans.user.user;
import service.SpringContextUtil;
import service.user.WXUserServiceImpl;

public class SubscribeThread extends Thread{
	private String name;
	public SubscribeThread(String name) {
		this.name=name;
	}
	public void run() {
		if(Configuration.isDebug())System.out.println("保存-"+name);
		//保存用户信息到数据库
		try {
			Weixin wx = new Weixin();
			wx.login(Configuration.getOAuthAppId(), Configuration.getOAuthSecret());//登录
			User u = wx.getUserInfo(name);
			//首先判断是否已经存在该用户
			WXUserServiceImpl<user> wxUserServiceImpl = (WXUserServiceImpl<user>)SpringContextUtil.getApplicationContext().getBean("WXUserServiceImpl");
			user temUser = wxUserServiceImpl.queryById(u.getOpenid());
			boolean has = true;
			if(temUser==null) {
				temUser = new user();
				has = false;
			}
			temUser.setOpenid(u.getOpenid());
			temUser.setCity(u.getCity());
			temUser.setCountry(u.getCountry());
			temUser.setGroupid(u.getGroupid());
			temUser.setHeadimgurl(u.getHeadimgurl());
			temUser.setLanguage(u.getLanguage());
			temUser.setNickname(u.getNickname());
			temUser.setOpenid(u.getOpenid());
			temUser.setProvince(u.getProvince());
			temUser.setRemark(u.getRemark());
			temUser.setSex(String.valueOf(u.getSex()));
			temUser.setSubscribe(u.getSubscribe());
			temUser.setSubscribe_time(new Date(u.getSubscribe_time()*1000L));
			temUser.setQr_scene_str(u.getQr_scene_str());

			String tagid_list = "";
			if(u.getTagid_list()!=null&&u.getTagid_list().length>0) {
				for(int i=0,j=u.getTagid_list().length;i<j;i++) {
					tagid_list += u.getTagid_list()[i]+",";
				}
			}

			temUser.setTagid_list(tagid_list);
			temUser.setUnionid(u.getUnionid());

			if(!has) {
				temUser.setId(UUID.randomUUID().toString());
				wxUserServiceImpl.add(temUser);
			}
			else {
				wxUserServiceImpl.update(temUser);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
